from flask import Blueprint, jsonify, request
from sqlalchemy.exc import NoResultFound

from app.services.food_service import FoodService
from app.models import FoodCategory

bp = Blueprint('food_routes', __name__)

foodService = FoodService()

@bp.route('/categories', methods=['GET'])
def get_categories():
    try:
        categories = FoodService.get_all_categories()
        return jsonify({'status': 'success', 'data': categories}), 200
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500

# 根据分类编码获取某个分类及其子分类
@bp.route('/categories/<category_code>', methods=['GET'])
def get_category_by_code(category_code):
    try:
        category = FoodService.get_category_by_code(category_code)
        if category:
            return jsonify({'status': 'success', 'data': category}), 200
        else:
            return jsonify({'status': 'error', 'message': 'Category not found'}), 404
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500


@bp.route('/categories/<int:category_id>/foods', methods=['GET'])
def get_foods_by_category(category_id):
    """ 返回指定类别ID下的所有食物 """
    # foods = FoodService.get_foods_by_category(category_id)
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    # foods, total = FoodService.get_foods_by_category(category_id, page, per_page)
    food_pagination,food_list = FoodService.get_foods_by_category(category_id, page, per_page)
    if page > food_pagination.pages:
        return jsonify({'message': 'Page out of range'}), 404
    if food_list:
        return jsonify({
        'total': food_pagination.total,
        'page': page,
        'per_page': per_page,
        'pages': food_pagination.pages,
        'foods': food_list,
        'per_page': per_page,
        'code': 'success'
    })
    else:
        return jsonify({'message': 'No foods found in this category'}), 404


@bp.route('/allcategory', methods=['GET'])
def get_allcategory():
    """ 获取所有食品类别 """
    categories = FoodCategory.query.all()
    return jsonify([category.category_name for category in categories])

@bp.route('/foods', methods=['GET'])
def get_foods():
    """ 获取所有食品 """
    foods = FoodService.get_all_foods()
    return jsonify([food.name for food in foods])

@bp.route('/meals', methods=['POST'])
def add_food_to_meal():
    try:
        # 从请求体中获取food_id和meal_id
        data = request.get_json()
        food_id = data.get('food_id')
        food_qty= data.get('food_qty')
        meal_id = data.get('meal_id')
        print(meal_id, food_id, food_qty)

        food_name, meal_header = foodService.add_food_to_meal(meal_id,food_id,food_qty)

        return jsonify({
            'message': f'{food_name} 添加到了 {meal_header}',
            'food_name': food_name,
            'meal_header': meal_header
        }), 200
    except ValueError as e:
        return jsonify({'error': str(e)}), 400
    except Exception as e:
        return jsonify({'error': e}), 500

# 删除 MealFood 记录
@bp.route('/meal_food', methods=['DELETE'])
def delete_meal_food():
    # 获取请求参数中的 meal_id 和 food_id
    meal_id = request.args.get('meal_id')
    food_id = request.args.get('food_id')
    # print(meal_id,food_id)
    # 检查参数是否提供
    if not meal_id or not food_id:
        return jsonify({"error": "meal_id and food_id are required"}), 400

    # 调用服务层的删除方法
    response, status_code = foodService.delete_meal_food(meal_id, food_id)

    return jsonify(response), status_code

@bp.route('/foods/<int:food_id>', methods=['GET'])
def get_food_by_id(food_id):
    """ 根据ID获取食品信息 """
    food = FoodService.get_food_by_id(food_id)
    if food:
        return jsonify({
            'name': food.name,
            'category': food.category,
            'calories': food.calories,
            # 添加其他字段
        })
    return jsonify({'message': 'Food not found'}), 404

@bp.route('/foods/<int:food_id>/similar', methods=['GET'])
def get_similar_foods(food_id):
    try:
        similar_foods = foodService.get_similar_foods(food_id)
        return jsonify({
            'status': 'success', 
            'data': similar_foods
        }), 200
    except NoResultFound:
        return jsonify({
            'status': 'error', 
            'message': 'Food not found'
        }), 404
    except Exception as e:
        return jsonify({
            'status': 'error', 
            'message': str(e)
        }), 500

@bp.route('/foods', methods=['POST'])
def add_food():
    """ 添加新商品 """
    data = request.get_json()
    food = FoodService.add_food(**data)
    return jsonify({'message': 'Food added successfully', 'food_id': food.food_id}), 201

@bp.route('/foods/<int:food_id>', methods=['PUT'])
def update_food(food_id):
    """ 更新商品信息 """
    data = request.get_json()
    food = FoodService.update_food(food_id, **data)
    if food:
        return jsonify({'message': 'Food updated successfully'})
    return jsonify({'message': 'Food not found'}), 404

@bp.route('/foods/<int:food_id>', methods=['DELETE'])
def delete_food(food_id):
    """ 删除商品 """
    if FoodService.delete_food(food_id):
        return jsonify({'message': 'Food deleted successfully'})
    return jsonify({'message': 'Food not found'}), 404

@bp.route('/search', methods=['GET'])
def search_foods():
    try:
        keyword = request.args.get('keyword', '', type=str)
        if not keyword:
            return jsonify({'status': 'error', 'message': 'Keyword is required'}), 400
        
        foods = foodService.search_foods_by_keyword(keyword)
        return jsonify({
            'code': 'success',
            'foods': foods,
            'total': len(foods)
        }), 200
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500
